/*
 * Copyright (C) 2011 Dirk Weißenborn, dirk.weissenborn@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.weissenborn.colabtex.server;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import com.weissenborn.colabtex.server.tex.TexUtil;

/**
 * The Class FileUploadServlet handles the upload of resources to the server
 */

public class FileUploadServlet extends HttpServlet {

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        super.doGet(req, resp);
    }

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
    	
    	if (ServletFileUpload.isMultipartContent(req)) {
	        // Create a factory for disk-based file items
	        FileItemFactory factory = new DiskFileItemFactory();
	
	        // Create a new file upload handler
	        ServletFileUpload upload = new ServletFileUpload(factory);
	
	        // Parse the request
	        try {
	            List<FileItem> items = upload.parseRequest(req);
	            for (FileItem item : items) {
	                // process only file upload - discard other form item types
	                if (item.isFormField()) continue;
	                
	                String fileName = item.getName();
	                // get only the file name not whole path
	                if (fileName != null) {
	                    fileName = FilenameUtils.getName(fileName);
	                }
	                
	                Cookie[] cookies = req.getCookies();
	                String padId = "";
	                for (int i = 0; i < cookies.length; i++) {
	            		if(cookies[i].getName().equalsIgnoreCase("padId")) {
	            			padId = cookies[i].getValue();
	            			break;
	            		}
	            			
	            	}
	
	                File uploadedFile = new File(TexUtil.getDirectory(padId), fileName);
	                while (!uploadedFile.createNewFile())
	                	uploadedFile.delete();
	                	
                    item.write(uploadedFile);
                    resp.setStatus(HttpServletResponse.SC_CREATED);
                    resp.getWriter().print("The file was created successfully.");
                    resp.flushBuffer();
	               
	            }
	        } catch (Exception e) {
	            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
	                    "An error occurred while creating the file : " + e.getMessage());
	        }
    	}
    	else
    		resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
    			                             "Request contents type is not supported by the servlet.");
    }
}